<?php

//APP授权模型
class MembersAccessModel extends BaseModel {

    //token生命周期,expired_time为过期时间
    protected $expired_time = 2678400;

    public function tableName() {
        return '{{members_access}}';
    }

    public function rules() {
        return array(
            array('uid', 'required', 'message' => '用户ID不能为空！'),
            array('token,create_time,expired_time', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $time = time();
            $this->create_time = $time;
            $this->expired_time = $time + $this->expired_time;
            $this->token = $this->createToken($this->uid);
        }
        return true;
    }

    //数据保存后回调
    protected function afterSave() {
        
    }

    /**
     * app用户端登录验证
     * @param type $username 用户名或者邮箱
     * @param type $pass 有明文密码会进行密码验证
     * @return boolean
     */
    public function login($username, $pass = NULL) {
        if (empty($username)) {
            return false;
        }
        $model = MembersModel::model();
        //判断登录方式
        if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $username)) {
            $userInfo = $model->find($model->where(array('email' => $username)));
        } else {
            $userInfo = $model->find($model->where(array('username' => $username)));
        }
        if (empty($userInfo)) {
            return false;
        }
        if ($userInfo->status == 0 || $userInfo->is_lock == 1) {
            $this->addError('', "该账号未激活或已经被锁定");
            return false;
        }
        //密码验证通过
        if (!is_null($pass) && !$userInfo->validatePassword($pass)) {
            $this->addError('', "账户或用户名错误请重新输入");
            return false;
        }
        //删除旧的授权记录
        $this->deleteAll($this->where(array('uid' => $userInfo->uid)));
        $userInfo->lastlogintime = time();
        $userInfo->save();
        //创建授权
        $this->uid = $userInfo->uid;
        $this->setIsNewRecord(true);
        if ($this->validate() && $this->insert()) {
            return ($this->attributes);
        }
        return false;
    }

    /**
     * 获取token
     * @param type $uid
     * @return string
     */
    public function getToken($uid) {
        if (empty($uid)) {
            return false;
        }
        $info = $this->findByPk($uid);
        if (empty($info)) {
            return false;
        }
        return $info->token;
    }

    /**
     * 根据token获取用户uid
     * @param type $token
     * @return boolean
     */
    public function getUid($token) {
        if (empty($token)) {
            return false;
        }
        $info = $this->find($this->where(array('token' => $token)));
        if (empty($info)) {
            return false;
        }
        //过期检查
        if ($this->verificationToken($token) !== true) {
            return false;
        } else {
            return $info->uid;
        }
//        $uid = Encrypt::authcode($token, 'DECODE');
//        if ($info->uid == $uid) {
//            return $info->uid;
//        }
//        return false;
    }

    /**
     * 生成token
     * @param type $uid
     * @return type
     */
    public function createToken($uid) {
        return md5(Encrypt::authcode($uid, ''));
    }

    /**
     * 验证token是否有效
     * @param type $token token值
     * @return boolean
     */
    public function verificationToken($token) {
        if (empty($token)) {
            return false;
        }
        $info = $this->find($this->where(array('token' => $token)));
        if (empty($info)) {
            return false;
        }
        if ($info->expired_time < time()) {
            $info->delete();
            return false;
        } else {
            return true;
        }
    }

}
